package com.service;

import com.MiaoshaResultType;
import com.config.RibbitMQConfig;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class MiaoshaService {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    @Qualifier("stringRedisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     *
     * @param uid       当前秒杀用户编号
     * @param goodsId   商品编号
     * @return
     * @throws InterruptedException
     */
    public String miaosha(String uid, String goodsId) throws InterruptedException {
        Object obj = redisTemplate.boundValueOps(uid + "::" + goodsId).get();
        if (obj != null) {
            return MiaoshaResultType.不能重复秒杀.name();
        }
       //加锁
        RLock rLock = redissonClient.getLock("miaosha");
        //rLock.lock();
        //rLock.unlock();

        boolean f = rLock.tryLock(3000,200, TimeUnit.MILLISECONDS);
        if (f==false)
        {
            return MiaoshaResultType.当前用户太多.name();
        }
        //判断库存
        Integer goods = (Integer)redisTemplate.boundValueOps("goods").get();
        if (goods==null)
        {
           return MiaoshaResultType.商品不存在.name();
        }

        //判断库存
        if (goods<0)
        {
            return MiaoshaResultType.库存不足.name();
        }

        //秒杀成功
        goods--;
        redisTemplate.boundValueOps("goods").set(goods);
        redisTemplate.boundValueOps(uid+"::"+goodsId).set("0",1,TimeUnit.HOURS);

        //发消息
        String msg = String.format("{uid:%s,goods:%s}", uid,goodsId);
        rabbitTemplate.convertAndSend(RibbitMQConfig.MIAOSHA_EXCHANGE,RibbitMQConfig.KEY_MIAOSHA, msg);

        return MiaoshaResultType.秒杀成功.name();
    }


}
